# -*- coding: utf-8 -*-
"""
SConstruct for building libsndfile as a static library for Android.
Tailored for the specific directory structure provided.
Usage: 
    scons platform=android target_arch=arm64-v8a
    scons platform=android target_arch=armeabi-v7a
"""

import os
import glob

# ===== 基础配置 (请根据你的实际情况修改) =====
# 设置你的 Android NDK 根目录路径
DEFAULT_NDK_ROOT = os.environ.get('ANDROID_NDK_ROOT', 'D:/tools/Android/SDK/ndk/28.1.13356709')
# 目标 Android API 级别
ANDROID_PLATFORM = 'android-21'
# 默认目标架构
DEFAULT_TARGET_ARCH = 'arm64-v8a'

# ===== 解析命令行参数 =====
target_platform = ARGUMENTS.get('platform', '')
target_arch = ARGUMENTS.get('target_arch', DEFAULT_TARGET_ARCH)
ndk_root = ARGUMENTS.get('ndk_root', DEFAULT_NDK_ROOT)

# ===== 初始化构建环境 =====
env = Environment(tools=['default'], PLATFORM="")

# ===== 根据平台配置 =====
if target_platform == 'android':
    print("Building libsndfile for Android: %s" % target_arch)
    
    env.Append(CCFLAGS=['-DHAVE_IO_H=0']) # 明确将 HAVE_IO_H 定义为 0，使其为假

    # 检查 NDK 路径
    if not os.path.isdir(ndk_root):
        print("错误: NDK 路径不存在 '%s'" % ndk_root)
        Exit(1)
    print("Using NDK: %s" % ndk_root)

    # 根据架构配置工具链
    if target_arch == 'arm64-v8a':
        clang_triple = 'aarch64-linux-android'
        toolchain_dir = os.path.join(ndk_root, 'toolchains', 'llvm', 'prebuilt', 'windows-x86_64')
    elif target_arch == 'armeabi-v7a':
        clang_triple = 'armv7a-linux-androideabi'
        toolchain_dir = os.path.join(ndk_root, 'toolchains', 'llvm', 'prebuilt', 'windows-x86_64')
    else:
        print("错误: 不支持的架构 '%s'" % target_arch)
        Exit(1)

    # 设置交叉编译工具路径
    clang_api_level = ANDROID_PLATFORM.replace('android-', '')
    cc = os.path.join(toolchain_dir, 'bin', '%s%s-clang' % (clang_triple, clang_api_level))
    cxx = os.path.join(toolchain_dir, 'bin', '%s%s-clang++' % (clang_triple, clang_api_level))
    ar = os.path.join(toolchain_dir, 'bin', 'llvm-ar')

    # 检查编译器是否存在
    if not os.path.isfile(cc):
        print("错误: 编译器不存在 '%s'" % cc)
        Exit(1)

    # 配置编译环境
    sysroot = os.path.join(toolchain_dir, 'sysroot')
    env.Replace(CC=cc)
    env.Replace(CXX=cxx)
    env.Replace(AR=ar)
    env.Append(CCFLAGS=[
        '--target=%s' % clang_triple,
        '--sysroot=%s' % sysroot,
        '-fPIC',  # Position Independent Code
        '-O2',
        '-DNDEBUG',
    ])
    env.Append(LINKFLAGS=[
        '--target=%s' % clang_triple,
        '--sysroot=%s' % sysroot,
    ])

    # 设置输出目录
    build_dir = 'build_android_%s' % target_arch
else:
    # 配置其他平台 (如 Windows) 或本地编译
    print("Building for default host platform")
    build_dir = 'build'
    env.Append(CCFLAGS=['-O2', '-DNDEBUG'])

# ===== 配置 libsndfile 源码编译 =====
# 头文件搜索路径 (根据提供的目录结构)
env.Append(CPPPATH=[
    '#include',  # libsndfile 的头文件目录
    '#src'       # src 目录可能也有内部头文件
])

# 收集源文件 (关键步骤！根据提供的目录结构调整)
# 主要编译 src 目录下的源文件
source_files = glob.glob('src/*.c')
# 排除可能存在的测试或工具源文件 (根据实际情况调整排除模式)
exclude_patterns = ['*test*.c', '*example*.c', 'sndfile-play.c', 'sndfile-info.c', 'sndfile-convert.c', 'sndfile-interleave.c']
for pattern in exclude_patterns:
    source_files = [f for f in source_files if pattern not in f]

print("Found %d source files in 'src/' directory." % len(source_files))

# 确保找到源文件
if not source_files:
    print("错误: 在 'src/' 目录下未找到任何源文件。")
    Exit(1)

# ===== 构建静态库 =====
# 创建静态库目标
static_lib = env.StaticLibrary(
    target=os.path.join(build_dir, 'libsndfile'),
    source=source_files
)

# ===== 设置为默认目标 =====
Default(static_lib)

# ===== 打印帮助信息 =====
Help("""
Build targets for libsndfile:
    platform=android       Build for Android (required for cross-compilation).
    target_arch=<arch>     Target architecture (e.g., arm64-v8a, armeabi-v7a). Default is arm64-v8a.
    ndk_root=<path>        Path to Android NDK root. Default is from ANDROID_NDK_ROOT environment variable or a predefined path.

Examples:
    scons platform=android target_arch=arm64-v8a
    scons platform=android target_arch=armeabi-v7a
    scons -c               Clean build products.
""")